import React from 'react';
import { List, InputItem, WhiteSpace, Button, Picker, DatePicker, WingBlank, Toast, Popup, Icon, TextareaItem } from 'antd-mobile';
import QRCode from 'qrcode.react';
import { createForm } from 'rc-form';
import { connect } from 'dva';
import _ from 'lodash';
import qs from 'query-string';
import moment from 'moment';
import { routerRedux } from 'dva/router';
import Container from '../components/Base/Container';
import Coming from './Coming';
import VerifyCodeItem from '../components/Base/VerifyCodeItem';
import { getOpenidByCode, fetchPaidVip, fetchShopWechat } from '../services/vipService';
import PaidVip from '../components/Base/PaidVip';

class RegPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      paidVip: null,
    };
  }

  toWechat = (shopId) => {
    fetchShopWechat(shopId).then((res) => {
      let appId;
      if (res.data) {
        appId = res.data.pay ? res.data.pay.appId : res.data.appId;
      }

      if (appId) {
        // 微信redirect_uri中不能出现hash，需要后台重定向
        const redirectUri = encodeURI("http://wx.hy-bang.com/wx/oauthRedirect");
        const state = JSON.stringify({ host: window.location.host, shopId, hash: 'addVip' });
        const scope = 'snsapi_base';
        const timestamp = (new Date()).getTime();
        const oauthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}&v=${timestamp}#wechat_redirect`;
        window.location.href = oauthUrl;
      }
    });
  }

  submit = () => {
    this.props.form.validateFields((error, value) => {
      if (error) {
        Toast.fail(_.map(error, (v) => {
          return _.get(v, 'errors[0].message');
        })[0], 1);
        return;
      }
      if (value.mobile) {
        value.mobile = value.mobile.replace(/\s/ig, '');
      }
      if (value.salesman) {
        const s = value.salesman[0].split('-');
        value.saleman_id = s[0];
        value.saleman_name = s[1];
        delete value.salesman;
      }
      if (value.vip_sex) {
        value.vip_sex = value.vip_sex[0];
      }
      if (value.birthday) {
        value.birthday = value.birthday.startOf('day');
      }
      value = _.pickBy(value, (v) => {
        return !_.isNil(v) && !_.isEmpty(v);
      });

      if (!_.isNil(value.paid_card_type)) {
        value.isPaidVip = true;
        value.cardType = value.paid_card_type[0] || value.paid_card_type;
        delete value.paid_card_type;
        value.quiet = true;
      }

      this.props.save(value);
    });
  };
  getSalemanData = () => {
    const { saleman_id, saleman_name } = this.props.location.query;
    if (saleman_id) {
      return [{ label: saleman_name, value: `${saleman_id}-${saleman_name}` }];
    }
    return _.map(this.props.saleman_list || [], (v) => {
      return { label: v.sale_name, value: `${v.sale_id}-${v.sale_name}` };
    });
  };
  renderSalemanSelect = () => {
    const saleman_id = this.props.saleman_id;
    const saleman_name = this.props.saleman_name;
    const initialValue = saleman_id ? [`${saleman_id}-${saleman_name}`] : [];
    return (<Picker
      title="选择导购"
      data={this.getSalemanData()}
      cols={1}
      {...this.props.form.getFieldProps('salesman', {
        initialValue,
        rules: [{ required: true, message: '请选择导购' }],
      })}
    >
      <List.Item arrow="horizontal">选择导购</List.Item>
    </Picker>);
  };

  qr = () => {
    const paramsData = {
      shopId: this.props.shopId,
      branch_no: this.props.branch_no,
      saleman_id: this.props.saleman_id,
      noBindCard: true,
    };
    if (this.state.paidVip && this.state.paidVip.enable) {
      paramsData.isPaidVip = true;
    }
    const params = qs.stringify(_.pickBy(paramsData, v => !_.isNil(v)));
    const url = `http://${location.host}/#/reg?${params}`;
    Popup.show(<div>
      <List
        renderHeader={item => (
          <div style={{ position: 'relative' }}>
              二维码
              <span
                style={{
                  position: 'absolute', right: 3, top: -5,
                }}
                onClick={() => {
                  Popup.hide();
                }}
              >
                <Icon type="cross" />
              </span>
          </div>)}
      >
        <div style={{ minHeight: '400px', overflowY: 'auto' }} className="am-flexbox am-flexbox-justify-center">
          <QRCode value={url} size={256} />
        </div>
      </List>
    </div>,
      { animationType: 'slide-up', maskProps: {}, maskClosable: true });
  };

  componentDidMount() {
    this.props.fetchSalesmanList();

    const shopId = this.props.shopId;
    fetchPaidVip(shopId).then((res) => {
      Toast.loading('请稍候...');

      if (res.data && res.data.length) {
        this.setState({
          paidVip: res.data[0],
        });

        const { location: { query: { code } } } = this.props;
        const { shopOpenid } = this.props;

        if (!code && !shopOpenid) {
          this.toWechat(shopId);
        } else if (code && code.length) {
          getOpenidByCode(code, shopId).then((result) => {
            if (result && result.data && result.data.openid) {
              this.props.updateShopOpenid(result.data.openid);
            }
          }).catch((error) => {
            console.error(error);
          });
        }
      }
    });
  }

  render() {
    const shopId = this.props.shopId;
    const { paidVip } = this.state;
    let isPaidVip = false;
    if (paidVip && paidVip.enable && paidVip.paidCardTypes && paidVip.paidCardTypes.length) {
      isPaidVip = true;
    }

    const branch_no = this.props.branch_no ? this.props.branch_no.split(',') : [];
   /* if (!(this.props.shopId === '000021' && (_.includes(branch_no, '000101') || _.includes(branch_no, '000080'))) &&
      ['13479041894', '15279681671', '15145208788', '18946200310', '13098909208', '13000000001', '13519892282', '13976620234', '13976817727',
        '15595618388'].indexOf(this.props.phone) === -1) {
      return <Coming />;
    }*/
    const { getFieldProps } = this.props.form;
    return (
      <Container
        navOption={{ rightContent: <div onClick={this.qr}>二维码</div> }}
        title="新增会员"
      >
        <div style={{ marginTop: '10%' }}>
          <WhiteSpace />
          <List>
            <InputItem
              {...getFieldProps('mobile', {
                rules: [{ required: true, message: '请输入手机号' }],
              })}
              type="phone"
              placeholder=""
            >手机号码</InputItem>

            <VerifyCodeItem
              reg={true}
              codeType="4"
              fieldName="verifyCode"
              phoneField="mobile"
              shopId={this.props.shopId}
              form={this.props.form}
            />

            <InputItem
              {...getFieldProps('vip_name', {
                rules: [{ required: true, message: '请输入会员姓名' }, { max: 4, message: '姓名长度不能超过4位' }],
              })}
              type="string"
              placeholder=""
            >会员姓名</InputItem>
            <Picker
              data={[
                {
                  label: '男',
                  value: '男',
                },
                {
                  label: '女',
                  value: '女',
                }]}
              cols={1}
              {...getFieldProps('vip_sex', {
                initialValue: ['男'],
                rules: [{ required: true, message: '请选择宝宝性别' }],
              })}
            >
              <List.Item arrow="horizontal">宝宝性别</List.Item>
            </Picker>
            <DatePicker
              mode="date"
              title="选择宝宝生日"
              maxDate={moment().add(2, 'years')}
              minDate={moment().subtract(12, 'years')}
              {...getFieldProps('birthday', {
                rules: [{ required: true, message: '请选择宝宝生日' }],
              })}
            >
              <List.Item arrow="horizontal">宝宝生日</List.Item>
            </DatePicker>
            {this.renderSalemanSelect()}
            <TextareaItem
              title="家庭地址"
              autoHeight
              {...getFieldProps('vip_add', {
                rules: [{ max: 80, message: '地址长度不能超过80位' }],
              })}
            />

            {
              isPaidVip && <PaidVip
                shopId={shopId}
                form={this.props.form}
                paidVip={paidVip}
              />
            }

          </List>
          <WhiteSpace size="xl" />
          <WingBlank>
            <Button type="primary" onClick={this.submit}>确定</Button>
          </WingBlank>
        </div>
      </Container>
    );
  }
}

export default connect((state) => {
  return {
    shopOpenid: state.auth.currentUser.shopOpenid,
    phone: state.auth.currentUser.phone,
    saleman_id: state.auth.currentUser.salemanId,
    saleman_name: state.auth.currentUser.saleManName,
    branch_no: state.auth.currentUser.branchNo,
    shopId: state.auth.currentUser.shopId,
    saleman_list: state.auth.saleman_list,
  };
}, (dispatch) => {
  return {
    updateShopOpenid: (shopOpenid) => {
      dispatch({ type: 'auth/updateShopOpenid', payload: { shopOpenid } });
    },
    fetchSalesmanList: () => {
      dispatch({ type: 'auth/fetch_saleman_list' });
    },
    save: (value) => {
      const data = {
        type: 'vip/create',
        payload: value,
      };
      if (value && value.quiet) {
        data.quiet = true;
      }
      dispatch(data);
    },
  };
})(createForm()(RegPage));

